import request from '@/utils/request'

export function getRoutes() {
  return request({
    url: '/user/getRoutes',
    method: 'get'
  })
}

export function listMenu(query) {
  return request({
    url: '/system/menu/getMenuList',
    method: 'get',
    params: query
  })
}

export function getMenuInfo(menuId) {
  return request({
    url: '/system/menu/' + menuId,
    method: 'get'
  })
}

export function handleTree(data, id, parentId, children) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }
  var childrenListMap = {}
  var nodeIds = {}
  var tree = []
  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }
  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }
  for (const t of tree) {
    adaptToChildrenList(t)
  }
  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

export function addMenuInfo(data) {
  return request({
    url: '/system/menu/addMenuInfo',
    method: 'post',
    data
  })
}

export function updateMenuInfo(data) {
  return request({
    url: '/system/menu/updateMenuInfo',
    method: 'put',
    data
  })
}

export function deleteMenuInfo(menuId) {
  return request({
    url: '/system/menu/' + menuId,
    method: 'delete'
  })
}
